package pattern.bio_httpserver;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

/**
 * @author xiawen yang
 * @date 2021/12/16 下午2:58
 */
public class BasicHttpServer {

    private static ExecutorService bootstrapExecutor = Executors.newSingleThreadExecutor();

    private static ExecutorService taskExecutor;

    private static final int PORT = 9099;


    static void startHttpServer() {
        int nThreads = Runtime.getRuntime().availableProcessors();
        taskExecutor = new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MICROSECONDS,
                new LinkedBlockingQueue<>(100), new ThreadPoolExecutor.DiscardOldestPolicy());

        while (true) {
            try {
                ServerSocket serverSocket = new ServerSocket(PORT);
                bootstrapExecutor.submit(new ServerThread(serverSocket));
                break;
            } catch (IOException e) {
                //重试
                try {
                    TimeUnit.SECONDS.sleep(10);
                } catch (InterruptedException interruptedException) {
                    Thread.currentThread().interrupt();
                }
            }
        }
    }

    private static class ServerThread implements Runnable {

        private ServerSocket serverSocket;

        public ServerThread(ServerSocket serverSocket) {
            this.serverSocket = serverSocket;
        }

        @Override
        public void run() {
            while (true) {
                try {
                    Socket socket = serverSocket.accept();
                    taskExecutor.submit(new HttpTask(socket));
                } catch (IOException e) {
                    e.printStackTrace();
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException interruptedException) {
                        Thread.currentThread().interrupt();
                    }
                }
            }
            // 一个客户端连接用一个线程去处理
        }
    }
}
